package com.trigsoft.applist;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Iterator;

import android.content.Context;

import com.trigsoft.utils.FileUtils;

public class NotInRecent
{
	static HashSet<String> nirList;
	private static String FILE = "not_in_recent";

	public NotInRecent(Context context)
	{
		if (nirList == null)
		{
			nirList = new HashSet<String>();

			try
			{
				BufferedReader in = new BufferedReader(new InputStreamReader(context.openFileInput(FILE)));
				try
				{
					String s;
					while ((s = in.readLine()) != null)
					{
						nirList.add(s);
					}
				} finally
				{
					in.close();
				}
			} catch (IOException e)
			{
				e.printStackTrace();
			}
		}
	}

	public void add(String pkg, String name)
	{
		// TODO Auto-generated method stub
		nirList.add(pkg + ":" + name);
	}

	public void save(Context context)
	{
		// TODO Auto-generated method stub
		StringBuilder sb = new StringBuilder();
		for (String s : nirList)
		{
			sb.append(s);
			sb.append("\n");
		}
		FileUtils.write(context, FILE, sb.toString());
	}

	public void addFromContext(String pkg, String name)
	{
		// TODO Auto-generated method stub
		if (name.compareTo("DEFAULT") == 0)
		{
			for (Iterator<String> is = nirList.iterator(); is.hasNext();)
			{
				if (is.next().contains(pkg + ":"))
					is.remove();
			}
		}
		add(pkg, name);
	}

	public void remove(String pkg, String name)
	{
		// TODO Auto-generated method stub
		boolean found = false;
		for (Iterator<String> is = nirList.iterator(); is.hasNext();)
		{
			if (is.next().contains(name))
			{
				is.remove();
				found = true;
				break;
			}
		}
		if (!found)
			nirList.remove(pkg + ":DEFAULT");
	}

	public boolean contains(String pkg, String name)
	{
		// TODO Auto-generated method stub
		for (String s : nirList)
		{
			if (s.contains(name) || s.contains(pkg + ":DEFAULT"))
				return true;
		}

		return false;
	}

	public String getText()
	{
		StringBuilder sb = new StringBuilder();
		for (String s : nirList)
		{
			sb.append(s);
			sb.append("\n");
		}
		return sb.toString();
	}

	public void importSetting(Context context, String text)
	{
		nirList = new HashSet<String>(Arrays.asList(text.split("\n")));
		save(context);
	}
}
